package com.ie.service.admin;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.common.security.utils.ConfigrarionBean;
import com.ie.common.security.utils.JwtTokenUtil;
import com.ie.common.security.utils.RedisUtil;
import com.ie.entity.AUserEntity;
import com.ie.mapper.admin.AUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author S2
 */
@Service
public class AUserServiceImpl extends ServiceImpl<AUserMapper, AUserEntity> implements AUserService {
    @Autowired
    private JwtTokenUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConfigrarionBean config;

    @Override
    public ResponseResult<Map<String, String>> login(AUserEntity aUserEntity) {
        Long res = lambdaQuery().eq(AUserEntity::getAname, aUserEntity.getAname())
                .count();
        if (res == 0) {
            return ResponseResult.getMessageResult(null, "A001");
        }
        Map<String, String> map = new HashMap<>();
        map.put("aname", aUserEntity.getAname());
        map.put("apwd", aUserEntity.getApwd());
        List<AUserEntity> adu = query().allEq(map).list();
        if (!adu.isEmpty()) {
            String token = jwtUtil.createToken(aUserEntity.getAname());
            redisUtil.set("login_" + aUserEntity.getAname(), aUserEntity.getAname(), config.getRedisExpiration());
            HashMap<String, String> myres = new HashMap<>();
            myres.put("authtoken", token);
            myres.put("aname", aUserEntity.getAname());
            myres.put("aid", adu.get(0).getId().toString());


            return ResponseResult.getSuccessResult(myres);
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }

    }
}
